package com.supor.aiot.mine.ui.cooking;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.launcher.ARouter;
import com.android.baseconfig.base.BaseApiResult;
import com.android.baseconfig.base.DataApiResult;
import com.android.baseconfig.base.RxBus3;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.arouter.PathUrl;
import com.supor.aiot.common.base.BaseMVVMEnhanceFragment;
import com.supor.aiot.mine.R;
import com.supor.aiot.mine.bean.CookingRecordBean;
import com.supor.aiot.mine.bean.CookingRecordItemBean;
import com.supor.aiot.mine.databinding.FragmentCookingRecordListBinding;
import com.supor.aiot.mine.ui.adapter.CookingRecordAdapter;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.functions.Consumer;

/**
 * @author: zook
 * @date: 2021/10/15
 */
public class CookingRecordListFragment extends BaseMVVMEnhanceFragment<CookingRecordModel, FragmentCookingRecordListBinding> {
    public static final String IS_EVAL = "IS_EVAL";
    public static final String MAC_ADR = "MAC_ADR";
    private CookingRecordAdapter cookingRecordAdapter;
    private int isEval;
    private int currentListPage;
    private String macAdr;

    public static CookingRecordListFragment newInstance(int isEval, String macAdr) {//1是已评价0是未评价 -1全部
        CookingRecordListFragment fragment = new CookingRecordListFragment();
        Bundle args = new Bundle();
        args.putInt(IS_EVAL, isEval);
        args.putString(MAC_ADR, macAdr);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (null != getArguments()) {
            isEval = getArguments().getInt(IS_EVAL);
            macAdr = getArguments().getString(MAC_ADR);
        }
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        RxBus3.getInstance().register(Constants.Tag.COOKING_EVAL, (Consumer<String>) s -> {
            loadData();
        }, this.getClass());
        cookingRecordAdapter = new CookingRecordAdapter();
        bindingView.rvContent.setLayoutManager(new LinearLayoutManager(getContext()));
        bindingView.rvContent.setAdapter(cookingRecordAdapter);

//        PinnedHeaderItemDecoration mHeaderItemDecoration = new PinnedHeaderItemDecoration
//                .Builder(CookingRecordItemBean.TYPE_YEAR)
//                .create();
//        bindingView.rvContent.addItemDecoration(mHeaderItemDecoration);
        bindingView.smartRefreshLayout.setEnableRefresh(false);
        bindingView.smartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                viewModel.getCookingRecordList(macAdr, isEval, ++currentListPage, bindDestoryAutoDispose());
            }
        });

        cookingRecordAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (cookingRecordAdapter.getData().get(position).getItemType() == CookingRecordItemBean.TYPE_ITEM) {

                }
            }
        });
        cookingRecordAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                if (cookingRecordAdapter.getData().size() > position) {
                    if (view.getId() == R.id.tv_eval) {
                        if (cookingRecordAdapter.getData().get(position).getIsEval() == 1) {
                            ARouter.getInstance().build(PathUrl.HomeMine.PATH_MINE_COOKING_EVAL_DETAIL)
                                    .withString("COOKING_EVAL_ID", cookingRecordAdapter.getData().get(position).getLogId())
                                    .withString("COOKING_EVAL_NAME", cookingRecordAdapter.getData().get(position).getFoodTRecipeVo().getRecipeName())
                                    .withString("COOKING_EVAL_IMG", cookingRecordAdapter.getData().get(position).getFoodTRecipeVo().getSmallLandscape())
                                    .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                                            com.android.baseconfig.R.anim.activity_open_exit)
                                    .navigation(getContext());
                        } else {
                            ARouter.getInstance().build(PathUrl.HomeMine.PATH_MINE_COOKING_EVAL)
                                    .withString("COOKING_EVAL_ID", cookingRecordAdapter.getData().get(position).getLogId())
                                    .withString("COOKING_EVAL_NAME", cookingRecordAdapter.getData().get(position).getFoodTRecipeVo().getRecipeName())
                                    .withString("COOKING_EVAL_IMG", cookingRecordAdapter.getData().get(position).getFoodTRecipeVo().getSmallLandscape())
                                    .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                                            com.android.baseconfig.R.anim.activity_open_exit)
                                    .navigation();
                        }
                    } else if (view.getId() == R.id.tv_cooking_copy) {
                        CookingRecordItemBean bean = cookingRecordAdapter.getData().get(position);
                        AppAgent.startRecipePage(bean.getRecipeId(), bean.getFoodTRecipeVo().getModelId());
                    }
                }
            }
        });
    }

    @Override
    protected void loadData() {
        super.loadData();
        if (currentListPage != 0) {
            cookingRecordAdapter.getData().clear();
            cookingRecordAdapter.notifyDataSetChanged();
            currentListPage = 0;
        }
        viewModel.getCookingRecordList(macAdr, isEval, ++currentListPage, bindDestoryAutoDispose());
//        bindingView.loadingView.setVisibility(View.VISIBLE);
//        bindingView.loadingView.playAnimation();
        showLoading();
    }

    @Override
    protected void initData() {
        super.initData();
        viewModel.getCookingRecordListResult().observe(this, new Observer<BaseApiResult<DataApiResult<List<CookingRecordBean>>>>() {
            @Override
            public void onChanged(BaseApiResult<DataApiResult<List<CookingRecordBean>>> dataApiResultBaseApiResult) {
//                cookingRecordAdapter.addData(dataApiResultBaseApiResult.data.rows);
                if (null != dataApiResultBaseApiResult.data && null != dataApiResultBaseApiResult.data.rows) {
                    recordDataFormat(dataApiResultBaseApiResult.data.rows);
                    bindingView.smartRefreshLayout.finishLoadMore();
                    if (dataApiResultBaseApiResult.data.getPage() >= dataApiResultBaseApiResult.data.getAllpages()) {
                        bindingView.smartRefreshLayout.setEnableLoadMore(false);
                    }
                    bindingView.dvMonthDayTopLine.setVisibility(View.VISIBLE);
                }
                if (currentListPage == 1 && (null == dataApiResultBaseApiResult.data || dataApiResultBaseApiResult.data.getTotal() == 0)) {
                    cookingRecordAdapter.setEmptyView(R.layout.layout_empty_cooking_record);
                    bindingView.dvMonthDayTopLine.setVisibility(View.GONE);
                }
                closeLoading();
//                bindingView.loadingView.cancelAnimation();
//                bindingView.loadingView.setVisibility(View.GONE);
            }
        });
    }

    private void recordDataFormat(List<CookingRecordBean> datas) {
        if (null == datas || datas.size() == 0) {
            return;
        }
        ArrayList<CookingRecordItemBean> tpDatas = new ArrayList<>();
        for (CookingRecordBean data : datas) {
            if (!TextUtils.isEmpty(data.getTime())) {
                CookingRecordItemBean cookingRecordBean = new CookingRecordItemBean();
                cookingRecordBean.setLocal_time(data.getTime());
                cookingRecordBean.setLocal_prcount(data.getPrcount());
                cookingRecordBean.setItemType(CookingRecordItemBean.TYPE_MONTH);
                tpDatas.add(cookingRecordBean);
                if (null != data.getLogVoList() && data.getLogVoList().size() > 0) {
                    tpDatas.addAll(data.getLogVoList());
                }
            }
        }
        cookingRecordAdapter.addData(tpDatas);
    }
}